#include "transportview.h"
#include <allegro5/allegro5.h>
#include <allegro5/allegro_primitives.h>
#include <iostream>
#include "font.h"
#include "app.h"
#include "song.h"
#include "knobskin.h"
using namespace std;

TransportView::TransportView(Font *pFont, Point start, App *pApp)
: View(Rect(), pFont), m_start(start), m_pApp(pApp), 
  m_tempoKnob(m_pApp->skin()->knobSkin(), m_start, Song::BpmMin, Song::BpmMax), 
  m_buttonDown(false), m_dragging(false) {
     m_tempoKnob.setPos(m_pApp->song()->bpm());
}

void TransportView::setStart(Point start) {
     m_start = start;
     m_tempoKnob.setStart(m_start);
}

Rect TransportView::rect() const {
     KnobSkin *pSkin = m_pApp->skin()->knobSkin();
     return Rect(m_start.x(), m_start.y(), pSkin->size(), pSkin->size());
}

void TransportView::paint(bool all) {
     Rect r = rect();
     // temporary - clear top of screen - update 0,0 to r.x() and r.y() later
     al_draw_filled_rectangle(0, 0, 
			      r.x() + r.width(), 
			      r.y() + r.height(),
			      al_map_rgb(0,0,0));
     m_tempoKnob.setPos(m_pApp->song()->bpm());
     m_tempoKnob.paint();
     m_needPaint = false;
}

void TransportView::mouseDown(Point p, int button) {
     if (button == 1) {
	  m_buttonDown = true;
	  m_dragging = true;
     }
}

void TransportView::mouseUp(Point p, int button) {
     if (button == 1) {
	  m_buttonDown = false;
	  m_dragging = false;
     }
}

void TransportView::mouseMove(Point p, Point dp) {
     // find out if button is still down - might have been released elsewhere
     ALLEGRO_MOUSE_STATE mouseState;
     al_get_mouse_state(&mouseState);
     m_buttonDown = al_mouse_button_down(&mouseState,1);
     if (m_buttonDown && m_dragging) {
	  m_pApp->song()->setBpm(m_pApp->song()->bpm() - dp.y());
	  m_pApp->player()->updateTempo();
	  refresh();
     } else {
	  m_grabMouse = false;
	  m_dragging = false;
     }
}

void TransportView::mouseExit(Point p) {
     if (m_dragging)
	  m_grabMouse = true;
}
